/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-19 15:32:38
 * @LastEditTime: 2022-05-19 16:11:29
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
 */
import { ref } from 'vue'
import sortTable from 'sortablejs'
import { updateArticleRanking } from '@/api/article'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n'
// 1. 创建 table 对象
export const tableRef = ref(null)

// 2. 创建拖拽函数
export const initSortTable = (tableData, cb) => {
  //  2.1. 设置 el 拖拽区域
  const el = tableRef.value.$el.querySelector('.el-table__body-wrapper tbody')

  sortTable.create(el, {
    //  2.2. 设置拖拽是类名
    ghostClass: 'sortable-ghost',
    //  2.3. 拖拽结束方法
    async onEnd({ newIndex, oldIndex }) {
      await updateArticleRanking(
        {
          initRanking: tableData.value[oldIndex].ranking,
          finalRanking: tableData.value[newIndex].ranking
        }
      )
      ElMessage.success(i18n.global.t('article.sortSuccess'))
      cb && cb()
    }
  })
}
